package com.xwj.xuthread.spring.core;

import com.xwj.xuthread.spring.enums.RejectedPolicyTypeEnum;
import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description TODO
 * @Author xwj
 * @Date 2025/8/24
 */
public class XuDynamicThreadPool extends ThreadPoolExecutor {

    @Getter
    @Setter
    private String threadPoolId;

    /**
     * 线程池拒绝策略执行次数
     */
    @Getter
    private final AtomicLong rejectCount = new AtomicLong();

    public XuDynamicThreadPool(){
        super(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(20), Executors.defaultThreadFactory(), RejectedPolicyTypeEnum.CALLER_RUNS_POLICY.getRejectedHandler());

        this.threadPoolId = "DEFAULT";

        setRejectedExecutionHandler(RejectedPolicyTypeEnum.CALLER_RUNS_POLICY.getRejectedHandler());
    }

    public XuDynamicThreadPool(String threadPoolId , int corePoolSize, int maximumPoolSize, long keepAliveTime, RejectedExecutionHandler handler, Integer capacity) {

        super(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingDeque<>(capacity), Executors.defaultThreadFactory(), handler);

        this.threadPoolId = threadPoolId;

        setRejectedExecutionHandler(handler);

    }

    @Override
    public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
        RejectedExecutionHandler handlerWrapper = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                rejectCount.incrementAndGet();
                handler.rejectedExecution(r, executor);
            }

            @Override
            public String toString() {
                return handler.getClass().getSimpleName();
            }
        };

        super.setRejectedExecutionHandler(handlerWrapper);
    }
}
